const Router = require('koa-router')
const Favorite = require('../schema/Favorite')
const tools = require('../utils/tools')

const favoriteRouter = new Router({
  prefix: '/nodeApi/favorite'
})

favoriteRouter.get('/findAll', async ctx => {
  let payload = tools.decode(ctx.header.authorization).payload;
  let favorites = await Favorite.find({
    opCode: payload.opCode
  }).populate('productId')
  ctx.body = favorites;
})

// TO-DO 关联查询有待研究
favoriteRouter.get('/findByPage', async ctx => {
  let query = {};
  let offset = ctx.query.offset;
  if (offset) {
    let searchText = ctx.query.searchText;
    if (searchText) {
      let searchReg = new RegExp(searchText)
      query.$or = [
        {
          title: { $regex: searchReg }
        },
        {
          sku: { $regex: searchReg }
        }
      ]
    }
    let favorites = await Favorite.paginate(query, {
      populate: 'productId',
      offset: offset,
      limit: 20
    })
    ctx.body = favorites;
  } else {
    ctx.body = {
      result: 'fail'
    }
  }
})

favoriteRouter.put('/new', async ctx => {
  let favorite = ctx.request.body
  let payload = tools.decode(ctx.header.authorization).payload;
  favorite.opCode = payload.opCode;
  favorite.opName = payload.opName;
  await new Favorite(favorite).save()
  ctx.body = {
    result: 'success'
  }
})

module.exports = favoriteRouter